﻿
using Newtonsoft.Json;

using System.Text;

namespace EvaluationSystem.Utils
{
    public class SessionToken
    {
        private const string _user_token = "user_token";

        public static bool GetUserToken(HttpContext context, out byte[]? value)
        {
            var r = context.Session.TryGetValue(_user_token, out var val);
            value = val;
            return r;
        }

        public static bool GetUserToken<T>(HttpContext context, out T? value) where T : new()
        {
            var r = GetUserToken(context, out var bytes);
            if (bytes == null)
            {
                value = default;
                return r;
            }
            value = BytesToObject<T>(bytes);
            return r;
        }

        public static void SetUserToken(HttpContext context, object? obj)
        {
            if (obj != null)
            {
                var bytes = ObjectToBytes(obj);
                context.Session.Set(_user_token, bytes);
            }
            else
            {
                context.Session.Remove(_user_token);
            }
        }

        /// <summary> 
        /// 将一个object对象序列化，返回一个byte[]         
        /// </summary> 
        /// <param name="obj">能序列化的对象</param>         
        /// <returns></returns> 
        public static byte[] ObjectToBytes(object obj)
        {
            var json = JsonConvert.SerializeObject(obj);
            return Encoding.Default.GetBytes(json);
        }

        /// <summary> 
        /// 将一个序列化后的byte[]数组还原         
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns> 
        public static T? BytesToObject<T>(byte[] bytes)
        {
            var str = Encoding.Default.GetString(bytes);
            var obj = JsonConvert.DeserializeObject<T>(str);
            return obj;
        }
    }
}
